package com._21cn.product.web.controller;

import com._21cn.cms.common.Constants;
import com._21cn.cms.common.FormSelector;
import com._21cn.cms.common.utils.DocumentUtil;
import com._21cn.framework.utils.DateUtil;
import com._21cn.framework.utils.StringUtil;
import com._21cn.product.entity.*;
import com._21cn.product.service.*;

import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.product.utils.ProductRelateHelper;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/admin/product/car")
public class CarController extends BaseController{

	private static String listView = "/admin/product/car/list";
    private static String showView = "/admin/product/car/show";
    private static String jsonView = "/admin/product/car/json";
    private static String formView = "/admin/product/car/form";
    private static String redirectListView = "redirect:/admin/product/car/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private CateService cateService;

    @Autowired
    private CarService carService;

    @Autowired
    private CarBusinessPledgeService carBusinessPledgeService;

    @Autowired
    private CarBusinessSecondService carBusinessSecondService;

    @Autowired
    private PropertyService propertyService;

    @Autowired
    private ProductRelateHelper productRelateHelper;
	
	@Autowired(required = false)
    @Qualifier("carValidator")
    private Validator carValidator;

    @RequestMapping("/push")
    @ResponseBody
    public String pushCar(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);

        String carIds = reqInfo.getParameter("carIds", null);
        String targetIds = reqInfo.getParameter("targetIds", null);
        Set<Integer> carIdSet = StringUtil.str2IntSet(carIds);
        Set<Integer> targetIdSet = StringUtil.str2IntSet(targetIds);

        for(Integer carId: carIdSet){
            CarBusinessSecond carBusinessSecond = productRelateHelper.getCarBusinessSecond(carId);
            CarBusinessPledge carBusinessPledge = productRelateHelper.getCarBusinessPledge(carId);
            if(carBusinessSecond.getId()>0){
                for(Integer targetId : targetIdSet){
                    productRelateHelper.push2RegionObj(targetId, carBusinessSecond.getId(), Constants.REGION_OBJECT_TYPE_SECOND);
                }
            }
            if(carBusinessPledge.getId()>0){
                for(Integer targetId : targetIdSet){
                    productRelateHelper.push2RegionObj(targetId, carBusinessPledge.getId(), Constants.REGION_OBJECT_TYPE_PLEDGE);
                }
            }
        }

        Map<String,Object> result = new HashMap<String,Object>();
        result.put("errorCode", Constants.RETURN_SUCCESS_CODE);
        result.put("message", "成功返回");
        return com.alibaba.fastjson.JSON.toJSONString(result);
    }

    @RequestMapping("/list")
    public String listCar(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", listView);
        model.addAttribute( "statusMap", FormSelector.getBusinessStatusMap());
        setRequestModelMap( request, model, true );
        return view;
    }

    @RequestMapping("/search")
    public String searchCar(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<Car> result = getPageList( model );
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
        return view;
    }

    @RequestMapping("/show")
    public String showCar(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", showView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            Car car = carService.getById( id );
            if( car == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
//            model.addAttribute( "statusMap", FormSelector.getStatusMap());
            model.addAttribute( "car", car );
        }
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/edit")
    public String editCar(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", formView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Car car = new Car();
        if( id > 0 ){
            car = carService.getById(id);
            if( car == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("eqStatus", Constants.STATUS_ENABLE);
        params.put("eqTypeId", Constants.CATE_TYPE_OTHER);
        params.put("orderByClause", "SORT_NUM ASC");
        List<Cate> otherList = cateService.getList(params, 1, 50);
        model.addAttribute( "otherList", otherList );

        params.clear();
        params.put("eqStatus", Constants.STATUS_ENABLE);
        params.put("eqTypeId", Constants.CATE_TYPE_PROPERTY);
        params.put("orderByClause", "SORT_NUM ASC");
        List<Property> propertyList = propertyService.getList(params, 1, 50);
        model.addAttribute( "propertyList", propertyList );

        Map<Integer, Object> propertyMap = new HashMap<Integer, Object>();
        if( !car.getCarPropertyList().isEmpty() ){
            for(CarProperty carProperty : car.getCarPropertyList()){
                Integer propertyId = carProperty.getPropertyId();
                String value = carProperty.getPropertyValue();
                propertyMap.put(propertyId, value);
            }
        }
        model.addAttribute( "propertyMap", propertyMap );

        CarBusinessPledge carBusinessPledge = productRelateHelper.getCarBusinessPledge(id);
        CarBusinessSecond carBusinessSecond = productRelateHelper.getCarBusinessSecond(id);

        model.addAttribute( "car", car );
        model.addAttribute( "carBusinessPledge" , carBusinessPledge);
        model.addAttribute( "carBusinessSecond" , carBusinessSecond);
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/save")
    public String saveCar(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Enumeration e = request.getParameterNames();

        Map<Integer, String> propertyMap = new HashMap<Integer, String>();                    //1、属性值
        while(e.hasMoreElements()){
            String name = (String) e.nextElement();
            if(name.contains("property_")){
                String[] ary = name.split("_");
                if( ary.length>1 ){
                    Integer pid = Integer.valueOf(ary[1]);
                    String value = request.getParameter(name);
                    propertyMap.put(pid, value);
                }
            }
        }
        String otherIds = reqInfo.getParameter("otherIds","");                  //2、其它类型
        String brandId = reqInfo.getParameter("brandId","");                    //3、品牌
        String seriesId = reqInfo.getParameter("seriesId","");                  //4、车系
        String[] imgUrls = request.getParameterValues("thumbPicUrl");           //5、图片列表

        List<Integer> otherIdList = StringUtil.str2IntList(otherIds);
        List<Integer> brandIdList = StringUtil.str2IntList(brandId);
        List<Integer> seriesIdList = StringUtil.str2IntList(seriesId);
        List<String> picList = new ArrayList<String>();
        if(imgUrls!=null && imgUrls.length>0){
            picList = new ArrayList<String>(Arrays.asList(imgUrls));
        }else{
            String details = reqInfo.getParameter("details", "");
            picList = DocumentUtil.getImageUrls(details);               //内容获取图片
        }

        //业务信息-二手车
        Float secondPrice_second =  reqInfo.getFloatParameter("secondPrice_second", 0.0f);
        Float odoMeter_second = reqInfo.getFloatParameter("odoMeter_second", 0.0f);
        Date dateOnBoard_second = DateUtil.parseDate(reqInfo.getParameter("dateOnBoard_second", ""));
        String areaOnBoard_second = reqInfo.getParameter("areaOnBoard_second", "");

        //业务信息-抵押车
        Float secondPrice_pledge =  reqInfo.getFloatParameter("secondPrice_pledge", 0.0f);
        Float odoMeter_pledge = reqInfo.getFloatParameter("odoMeter_pledge", 0.0f);
        Date dateOnBoard_pledge = DateUtil.parseDate(reqInfo.getParameter("dateOnBoard_pledge", ""));
        String areaOnBoard_pledge = reqInfo.getParameter("areaOnBoard_pledge", "");

        Integer carId = 0;
        if( id>0 ){                                         //更新
            Car car = carService.getById( id );
            if( bind( request, car, model,  carValidator).hasErrors() ){
                return formView;
            }
            car.setModifyTime(new Date());
            carService.update( car );
            carId = car.getId();
            productRelateHelper.updatePropertyMap(propertyMap, carId, Constants.CATE_TYPE_PROPERTY);
            productRelateHelper.updateCarCateList(otherIdList,carId,Constants.CATE_TYPE_OTHER);
            productRelateHelper.updateCarCateList(brandIdList,carId,Constants.CATE_TYPE_BRAND);
            productRelateHelper.updateCarCateList(seriesIdList,carId,Constants.CATE_TYPE_SERIES);
            productRelateHelper.updatePicList(picList, carId);
        }else{                                              //添加
            Car car = new Car();
            if( bind( request, car, model,  carValidator).hasErrors() ){
                return formView;
            }
            carService.insert( car );
            carId = car.getId();
            productRelateHelper.insertPropertyMap(propertyMap, carId, Constants.CATE_TYPE_PROPERTY);
            productRelateHelper.insertCarCateList(otherIdList,carId,Constants.CATE_TYPE_OTHER);
            productRelateHelper.insertCarCateList(brandIdList,carId,Constants.CATE_TYPE_BRAND);
            productRelateHelper.insertCarCateList(seriesIdList,carId,Constants.CATE_TYPE_SERIES);
            productRelateHelper.insertPicList(picList, carId);
        }
        //6、添加业务信息
        if( secondPrice_second>0 ){
            productRelateHelper.updateSecondCar(carId, secondPrice_second, odoMeter_second, dateOnBoard_second, areaOnBoard_second);
        }
        if( secondPrice_pledge>0 ){
            productRelateHelper.updatePledgeCar(carId, secondPrice_pledge, odoMeter_pledge, dateOnBoard_pledge, areaOnBoard_pledge);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }
	
	@RequestMapping("/updateStatus")
    public String updateCarStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        if( status < 0 ){
            model.clear();
            return redirectListView+ "?" + reqInfo.getParameter( "queryParam", "" );
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            carService.update( model );
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("status", status);
            params.put("inCarIds", objectIds);
            carBusinessPledgeService.update(params);
            carBusinessSecondService.update(params);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/delete")
    public String deleteCar(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            carService.delete( model );
            productRelateHelper.deleteCarRelate(StringUtil.str2IntList(objectIds));
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping("/select")
    public String selectSite(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<Car> result = getPageList( model );
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
        return view;
    }

	private PageList<Car> getPageList(ModelMap model) {
        if(model.containsKey("likeName"))
            model.put("likeName",model.get("likeName").toString().toLowerCase());
        model.addAttribute("orderByClause", "ID desc");

        PageList<Car> carList = carService.getList( model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()) );
        PageList<Car> resultList = new PageList<Car>();
        for( Car car : carList ){
            car = carService.getById(car.getId(), true);
            CarBusinessSecond carBusinessSecond = productRelateHelper.getCarBusinessSecond(car.getId());
            CarBusinessPledge carBusinessPledge = productRelateHelper.getCarBusinessPledge(car.getId());

            String businessIds = "";
            String businessTypeStr = "";
            if(carBusinessSecond.getId()>0){
                businessIds = carBusinessSecond.getId()+"";
                businessTypeStr = "二手车";
            }
            if(carBusinessPledge.getId()>0){
                businessIds = carBusinessPledge.getId()+"";
                businessTypeStr = "抵押车";
            }
            car.setBusinessIds(businessIds);
            car.setBusinessTypeStr(businessTypeStr);
            resultList.add(car);
        }

        resultList.setPageTurn(carList.getPageTurn());

        model.addAttribute( "carList", resultList);
        model.addAttribute( "objList", resultList);
        model.addAttribute( "pageTurn", resultList.getPageTurn());
        model.addAttribute( "titleMap", getPropertyTitleMap() );
        return resultList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if( propertyTitleMap == null ){
			propertyTitleMap = new HashMap<String,String>();
			propertyTitleMap.put( "id", "id" );
			propertyTitleMap.put( "name", "name" );
			propertyTitleMap.put( "nameShort", "nameShort" );
			propertyTitleMap.put( "keyword", "keyword" );
			propertyTitleMap.put( "firstPicUrl", "firstPicUrl" );
			propertyTitleMap.put( "details", "details" );
			propertyTitleMap.put( "sortNum", "sortNum" );
			propertyTitleMap.put( "status", "status" );
			propertyTitleMap.put( "clickNum", "clickNum" );
			propertyTitleMap.put( "shareNum", "shareNum" );
			propertyTitleMap.put( "goodNum", "goodNum" );
			propertyTitleMap.put( "badNum", "badNum" );
			propertyTitleMap.put( "createUserId", "createUserId" );
			propertyTitleMap.put( "createTime", "createTime" );
			propertyTitleMap.put( "modifyUserId", "modifyUserId" );
			propertyTitleMap.put( "modifyTime", "modifyTime" );
        }
        return propertyTitleMap;
    }
}
